let listLoad = require('../../common/mixinList');
Page({
    behaviors: [listLoad],
    data: {
        navInfo: null,
        upAndDownInfo: null,
        reqUrl: '/api/product/index',
        cate_id: '', //分类Id
        color_id: '', //颜色ID
        product_common_id: '',
        goodsPropsList: [], //获取到的商品可选择属性列表
        radio_sort: 0, //选中的排序
        screenPopupShow: false, //筛选弹出层
        attr_value_id: '', //筛选选中的属性值ID
        attr_value_name: '', //筛选选中的属性值
        showAddCartPopup: false, //展示加入购物车弹窗
        addCartCurrent: null, //加入购物车商品信息
        usePrivateMethod: true,
        sortOption: [
            { text: '默认', value: 0 },
            { text: '价格', value: 1 },
            { text: '销量', value: 2 },
            { text: '等级从低到高', value: 3 },
            { text: '等级从高到低', value: 4 },
        ],
        cartCheckNum: 0, //购物车数量
    },
    onLoad: function (options) {
        const cartCheckNum = getApp().globalData.cartCheckNum;
        this.setData({ navInfo: getApp().globalData.navInfo, cartCheckNum });
        const { uid, keyWords, cate_id, color_id, product_common_id } = options;
        if (uid) {
            //页面分享携带uid绑定关系
            return this.redirect_login(options.uid);
        }
        let data = {};
        if (keyWords) data.searchText = keyWords;
        if (cate_id) data.cate_id = cate_id;
        if (color_id) data.color_id = color_id;
        if (product_common_id) data.product_common_id = product_common_id;

        this.setData(data);
        this.getList(true);

        product_common_id && this.getUpAndDownInfo(product_common_id);
        this.getGoodsProp();
    },
    onReady() {
        getApp().watchGlobalData('cartCheckNum', value => {
            this.setData({ cartCheckNum: value });
        });
    },
    getParamsData() {
        //页面特殊的请求参数，需要时在页面内覆盖此方法，默认返回{}
        const {
            cate_id,
            color_id,
            product_common_id,
            searchText,
            attr_value_id,
            radio_sort,
            radio_level,
            level_sort,
        } = this.data;
        let params = { limit: 8 };
        if (cate_id) params.cate_id = cate_id;
        if (color_id) params.color_id = color_id;
        if (product_common_id) params.product_common_id = product_common_id;
        if (searchText) params.so = searchText;
        if (attr_value_id !== '') params.attr_value_id = attr_value_id;
        if (radio_sort !== 0)
            params.order = ['', 'price', 'sales', 'level_desc', 'level_asc'][
                radio_sort
            ];

        return params;
    },
    privateMethod(refresh, res) {
        return new Promise(resolve => {
            if (res.data.length === 0) return resolve([]);
            if (!this.data.product_common_id && !this.data.upAndDownInfo) {
                const { product_common_id } = res.data[0];
                this.getUpAndDownInfo(product_common_id);
            }
            res.data.forEach(item => {
                let newData = {
                    product_name: item.product_name,
                    color: item.color,
                    level: item.level,
                    norm: item.norm,
                    unit: item.unit,
                    sales: item.sales,
                    day_count: item.day_count,
                    sku: item.sku,
                    supplier_id: item.supplier_id,
                    supplier: {
                        title: item.supplier.title,
                        supplier_id: item.supplier.supplier_id,
                        avg_score: item.supplier.avg_score,
                        tag_list: item.supplier.tag_list,
                    },
                    sale_rate: item.sale_rate,
                    product_img: item.product_img,
                    product_id: item.product_id,
                    product_price: item.product_price,
                    collected: item.collected,
                    original_price: item.original_price,
                };
                [
                    newData.product_price_int,
                    newData.product_price_float,
                ] = item.product_price.toString().split('.');
                item = newData;
            });
            resolve(res.data);
        });
    },
    //获取涨跌信息
    getUpAndDownInfo(product_common_id) {
        this.request(
            {
                url: `/api/index/rateProduct?product_common_id=${product_common_id}`,
                login: false,
            },
            res => {
                if (Number(res.data.change_rate) === 0) {
                    res.data.isUp = false;
                    res.data.upAndDownPrice = 0;
                    res.data.change_rate = '-' + res.data.change_rate;
                } else {
                    let upAndDownPrice = Number(
                        (
                            res.data.today_price -
                            Number(res.data.yesterday_price)
                        ).toFixed(2)
                    );
                    res.data.isUp = upAndDownPrice > 0;
                    res.data.upAndDownPrice = Math.abs(upAndDownPrice);
                }
                this.setData({ upAndDownInfo: res.data });
            }
        );
    },
    //获取商品属性选项列表
    getGoodsProp() {
        this.request(
            {
                url: '/api/product/attr',
                login: false,
            },
            res => {
                res.data.forEach(item => {
                    item.active = null; //生效的属性索引
                });
                this.setData({ goodsPropsList: res.data });
            }
        );
    },
    //点击排序、等级
    openSortPopup({ currentTarget }) {
        const { field } = currentTarget.dataset;
        this.setData({
            sortPopupShow: false,
            levelPopupShow: false,
            [field]: !this.data[field],
        });
    },
    //点击排序选项
    onSortTap(event) {
        this.setData({
            radio_sort: event.detail,
            list: [],
        });
        this.getList(true);
    },
    //点击等级选项
    onLevelChange(event) {
        this.setData({
            radio_level: event.detail,
            list: [],
        });
        this.getList(true);
    },
    //点击筛选
    openScreenPopup() {
        this.setData({ screenPopupShow: true });
    },
    //选择商品属性
    chooseAttr({ mark }) {
        const { index, childrenIndex } = mark;
        if (childrenIndex == undefined) return;
        let { goodsPropsList } = this.data;
        goodsPropsList.forEach(item => {
            item.active = null;
        });
        goodsPropsList[index].active = childrenIndex;
        this.setData({
            goodsPropsList,
            attr_value_id:
                goodsPropsList[index].attr_value[goodsPropsList[index].active]
                    .attr_value_id,
            attr_value_name:
                goodsPropsList[index].attr_value[goodsPropsList[index].active]
                    .attr_value_name,
            screenPopupShow: false,
            list: [],
        });
        this.getList(true);
    },
    //重置商品属性
    reset() {
        let { goodsPropsList, attr_value_id } = this.data;
        if (attr_value_id === '')
            return this.setData({ screenPopupShow: false });
        goodsPropsList.forEach(item => {
            item.active = null;
        });
        this.setData({
            goodsPropsList,
            attr_value_id: '',
            attr_value_name: '',
            screenPopupShow: false,
            list: [],
        });
        this.getList(true);
    },
    operation({ mark }) {
        const { index, addCart } = mark;
        if (index == undefined) return;
        if (addCart) {
            return this.openAddcartPopup(index);
        }
        this.toDetail(index);
    },
    //前往商品详情
    toDetail(index) {
        wx.navigateTo({
            url: `/pages/good_detail/index?id=${this.data.list[index].product_id}`,
        });
    },
    toEchart() {
        const { upAndDownInfo } = this.data;
        wx.navigateTo({
            url: `/pages/conjuncture_echarts/index?cate_id=${upAndDownInfo.cate_id}&product_common_id=${upAndDownInfo.product_common_id}&title=${upAndDownInfo.product_name}`,
        });
    },
    /**点击加入购物车 */
    openAddcartPopup(index) {
        const info = this.data.list[index];

        if (info.sku === 0)
            return wx.showToast({
                title: '该商品已售空',
                icon: 'none',
            });
        const { imgHost } = this.data;
        const addCartCurrent = {
            product_img: imgHost + info.product_img,
            product_name: info.product_name,
            product_price: info.product_price,
            sku: info.sku,
            unit: info.unit,
            supplier_id: info.supplier.supplier_id,
            supplier_name: info.supplier.title,
            level: info.level,
            norm: info.norm,
            product_id: info.product_id,
            sell_num: info.sell_num,
        };

        this.setData({
            addCartCurrent,
            showAddCartPopup: true,
        });
    },
    //点击分享
    onShareAppMessage({ from }) {
        const promise = new Promise(resolve => {
            if (from === 'button') {
                //转发商品详情
                const { list, imgHost, userInfo } = this.data;
                this.delay(() => {
                    let options = `/pages/good_detail/index?id=${
                        list[this.data.shareCurrent].product_id
                    }`;
                    if (userInfo) options += `&uid=${userInfo.uid}`;
                    let title = `Hi~我向你推荐了${
                        list[this.data.shareCurrent].product_name
                    }，快点击查看吧！`;

                    resolve({
                        path: options,
                        title,
                        imageUrl:
                            imgHost + list[this.data.shareCurrent].product_img,
                    });
                }, 200);
            } else {
                //分享页面
                const {
                    userInfo,
                    searchText,
                    cate_id,
                    color_id,
                    product_common_id,
                } = this.data;
                let options = '/pages/hall_goods/index?x=x';
                if (userInfo) options += `&uid=${userInfo.uid}`;
                if (searchText) options += `&keyWords=${searchText}`;
                if (cate_id) options += `&cate_id=${cate_id}`;
                if (color_id) options += `&color_id=${color_id}`;
                if (product_common_id)
                    options += `&product_common_id=${product_common_id}`;

                resolve({
                    path: options,
                    title: '向你推荐了云花街，快点击查看吧！',
                });
            }
        });

        return {
            promise,
        };
    },
    pageBack() {
        wx.navigateBack();
    },
});
